package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.department;

import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.enums.RespCodeEnum;
import com.cqhilink.iot.jobstandardmanagement.facade.service.permission.JsmRolesService;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.BackMessage;
import com.cqhilink.iot.jobstandardmanagement.common.enums.*;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.DepartmentMapper;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.OrganizationMapper;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.OrganizationLevel;
import com.cqhilink.iot.jobstandardmanagement.facade.model.*;
import com.cqhilink.iot.jobstandardmanagement.facade.service.department.JsmDepartmentService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.organization.JsmOrganizationService;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.TreeIconSkin;
import com.cqhilink.iot.jobstandardmanagement.services.innerservice.util.DepartmentUtil;
import com.cqhilink.iot.jobstandardmanagement.facade.service.employee.JsmEmployeeService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @version V1.0
 * @Package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.department
 * @Description: ${TODO}(组织部门业务逻辑处理类)
 * @author: Yu Peng
 * @date: 2016/11/28,0016
 */
public class JsmDepartmentServiceImpl implements JsmDepartmentService {
    public Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final int ORG_LEVEL_MAX_FOUR = 4;
    private static final int ORG_LEVEL_MAX_FIVE = 5;
    //注入部门DAO
    @Autowired
    private DepartmentMapper departmentMapper;
    //注入组织机构DAO
    @Autowired
    private OrganizationMapper organizationMapper;
    //注入员工SERVICE
    @Autowired
    private JsmEmployeeService employeeService;
    @Autowired
    private JsmOrganizationService jsmOrganizationService;
    @Autowired(required = false)
    private JsmRolesService rolesService ;

    /**
     * 加载所有组织部门树
     */
    public List<Ztree> selectAllDept() throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        List<Department> departments = departmentMapper.selectAll();
        if (ztreeList != null) {
            for (Department dept : departments) {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDepId());
                ztree.setName(dept.getDepName());
                ztree.setIconSkin(TreeIconSkin.ICON_DEPT.getDesc());
                if (StringUtils.isEmpty(dept.getParentDepId())) {
                    ztree.setpId(dept.getParentOrgId());
                } else {
                    ztree.setpId(dept.getParentDepId());
                }
                ztreeList.add(ztree);
            }
        }
        return ztreeList;
    }


    /**
     * @param orgId 组织机构id
     */
    @Override
    public List<Ztree> queryDeptByOrgId(String orgId) throws Exception {
        List<Ztree> list = new ArrayList<>();
        List<Department> departments = departmentMapper.selectDeptByOrgId(orgId);
        if (departments != null) {
            for (Department department : departments) {
                Ztree ztree = new Ztree();
                ztree.setId(department.getDepId());
                ztree.setName(department.getDepName());
                if (department.getParentDepId() != null) {
                    ztree.setpId(department.getParentDepId());
                } else {
                    ztree.setpId(department.getParentOrgId());
                }
                ztree.setIconSkin(TreeIconSkin.ICON_DEPT.getDesc());
                ztree.setIsParent(true);
                ztree.setOpen(false);
                list.add(ztree);
            }
        }
        return list;
    }

    /**
     * 部门树
     *
     * @return
     * @throws Exception
     */
    public List<Ztree> queryDeptTree(String isOrg, String id, String keyword) throws Exception {
        //注意：数据库中分公司的上级ID一定是0！，否则会显示错误！
        List<Ztree> ztList = new ArrayList<Ztree>();
        if (StringUtils.isBlank(id)) {
            if (!StringUtils.isBlank(keyword)) {
                Organization organization = new Organization();
                organization.setKeyword(keyword);
                List<Organization> orgList = organizationMapper.selectOrgList(organization);
                if (orgList.size() > 0) {
                    for (Organization org : orgList) {
                        List<DepartmentVO> depList = departmentMapper.findOrgKeyword(keyword);
                        ztList.addAll(queryDeptTreeByDeptList(depList));
                    }
                    ztList.addAll(queryDeptTreeByOrgList(orgList, ORG_LEVEL_MAX_FOUR, 1));
                } else {
                    List<DepartmentVO> depList = departmentMapper.findOrgKeyword(keyword);
                    ztList.addAll(queryDeptTreeByDeptList(depList));
                    if (depList.size() > 0) {
                        for (DepartmentVO dep : depList) {
                            organization.setKeyword(null);
                            organization.setOrgId(dep.getParentOrgId());
                            List<Organization> orgLists = organizationMapper.selectOrgList(organization);
                            ztList.addAll(queryDeptTreeByOrgList(orgLists, ORG_LEVEL_MAX_FOUR, 1));
                        }
                    }
                }
            } else {
                List<Organization> orgList = organizationMapper.selectOrgByLevel("2");
                ztList.addAll(queryDeptTreeByOrgList(orgList, ORG_LEVEL_MAX_FOUR, 1));
            }
        } else {
            if ("1".equals(isOrg)) {
                //组织
                ztList.addAll(queryDeptTreeByPOId(id, 1));
            } else {
                ztList.addAll(queryDeptTreeByPDId(id));
            }
        }
        return ztList;
    }

    /**
     * 根据ID查询
     *
     * @param deptId
     * @return
     */
    @Override
    public Department selectById(String deptId) {
        return departmentMapper.selectById(deptId);
    }


    /**
     * 加载组织所有的组织部门
     */
    @Override
    public List<Ztree> loadDeptTree() throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        List<Department> departments = departmentMapper.selectAll();
        if (departments != null) {
            for (Department dept : departments) {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDepId());
                ztree.setName(dept.getDepName());
                ztree.setpId(dept.getParentDepId());
            }
        }
        return ztreeList;
    }

    /**
     * 查询部门树，并将父级加入到树中
     *
     * @param isOrg
     * @param pid
     * @return
     * @throws Exception
     */
    @Override
    public List<Ztree> queryDeptTreeWithParent(String isOrg, String pid) throws Exception {
        List<Ztree> ztList = new ArrayList<Ztree>();
        if (!StringUtils.isBlank(isOrg) && "1".equals(isOrg)) {
            ztList.addAll(queryDeptTreeByPOId(pid, 1));
        }
        return ztList;
    }

    /**
     * 按所属部门ID查询部门树
     *
     * @return
     * @throws Exception
     */
    public List<Ztree> queryDeptTreeByPDId(String deptId) throws Exception {
        List<Ztree> ztList = new ArrayList<Ztree>();
        List<DepartmentVO> deptList = departmentMapper.selectByPDId(deptId);
        ztList.addAll(queryDeptTreeByDeptList(deptList));
        return ztList;
    }

    /**
     * 按所属机构ID查询部门树
     */
    public List<Ztree> queryDeptTreeByPOId(String orgId, int isNum) throws Exception {
        List<Ztree> ztList = new ArrayList<Ztree>();
        //查询当前组织机构
        Organization org = organizationMapper.selectOrgByOrgId(orgId);
        List<Organization> orgList = null;
        //
        int levelId = Integer.parseInt(org.getOrgLevelId());
        if (levelId <= ORG_LEVEL_MAX_FOUR) {
            orgList = organizationMapper.selectOrgByOrgPId(orgId);
            if (levelId == ORG_LEVEL_MAX_FOUR) {
                Iterator<Organization> it = orgList.iterator();
                while (it.hasNext()) {
                    Organization o = it.next();
                    if (!OrganizationLevel.ORG_LEVEL_STATION.getCode().equals(o.getOrgLevelId())) {
                        it.remove();//去掉非场站数据
                    }
                }
            }
        }
        //查询部门
        List<DepartmentVO> deptList = departmentMapper.selectByPOId(orgId);
        ztList.addAll(queryDeptTreeByDeptList(deptList));
        if (orgList != null && orgList.size() > 0) {
            ztList.addAll(queryDeptTreeByOrgList(orgList, ORG_LEVEL_MAX_FIVE, isNum));
        }
        return ztList;
    }

    /**
     * 将组织机构list信息转换为组织树
     *
     * @param orgList
     * @return
     * @throws Exception
     */
    private List<Ztree> queryDeptTreeByOrgList(List<Organization> orgList, int isLevel, int isNum) throws Exception {
        List<Ztree> demotree = new ArrayList<Ztree>();
        //遍历组织机构list
        for (Organization org : orgList) {
            Ztree demo = new Ztree();
            //设置ID
            demo.setId(org.getOrgId());
            //设置上级ID
            demo.setpId(org.getParentOrgId());
            //设置名称
            demo.setName(org.getOrgName());
            //设置机构层级
            demo.setOrgLevel(org.getOrgLevelId());
            //设置是否机构标识
            demo.setIsOrg(1);
            //设置默认图标
            demo.setIconSkin(TreeIconSkin.ICON_STATION.getDesc());
            //判断组织机构层级，并设置图标
            if (OrganizationLevel.ORG_LEVEL_BRANCH.getCode().equals(org.getOrgLevelId())) {
                demo.setIconSkin(TreeIconSkin.ICON_BUIDING.getDesc());
            }
            if (OrganizationLevel.ORG_LEVEL_GAS_FIELD.getCode().equals(org.getOrgLevelId())) {
                demo.setIconSkin(TreeIconSkin.ICON_FLAG.getDesc());
            }
            if (OrganizationLevel.ORG_LEVEL_WORK_SPACE.getCode().equals(org.getOrgLevelId())) {
                demo.setIconSkin(TreeIconSkin.ICON_OA.getDesc());
                demo.setOpen(RespCodeEnum.RESP_CODE_ENUM_false.code());
            }
            //判断是否含有下属机构，含有则为true，没有则为false
            int orgLevel = Integer.parseInt(org.getOrgLevelId());
            if (orgLevel < isLevel) {
                int orgNum = 0;
                if (orgLevel < isLevel) {
                    if (isNum == 1 && (orgLevel == 3 || orgLevel == 4)) {
                        //当isNum等于1的时候判断当前节点下面有场站才让当前节点能继续展示下级，
                        List<Organization> lists = organizationMapper.selectListByPOId(org.getOrgId());
                        if (lists != null && lists.size() > 0) {
                            for (Organization o : lists) {
                                if (OrganizationLevel.ORG_LEVEL_STATION.getCode().equals(o.getOrgLevelId())) {
                                    orgNum = 1;
                                    break;
                                }
                            }
                        }
                    } else {
                        orgNum = organizationMapper.selectCountByPOId(org.getOrgId());
                    }
                }
                //判断是否有下级
                int deptNum = departmentMapper.selectCountByPOId(org.getOrgId());
                boolean isParent = orgNum > 0 || deptNum > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code();
                demo.setIsParent(isParent);
                demotree.add(demo);
            }
        }
        return demotree;
    }

    /**
     * 将部门列表转换为部门树实体
     *
     * @param deptList
     * @return
     * @throws Exception
     */
    private List<Ztree> queryDeptTreeByDeptList(List<DepartmentVO> deptList) throws Exception {
        List<Ztree> demotree = new ArrayList<Ztree>();
        //遍历部门list
        for (DepartmentVO dept : deptList) {
            Ztree demo = new Ztree();
            demo.setId(dept.getDepId());
            if (!StringUtils.isBlank(dept.getParentDepId())) {
                demo.setpId(dept.getParentDepId());
            } else if (!StringUtils.isBlank(dept.getParentOrgId())) {
                demo.setpId(dept.getParentOrgId());
            }
            demo.setName(dept.getDepName());
            demo.setIsOrg(0);
            //设置图标
            demo.setIconSkin(TreeIconSkin.ICON_DEPT.getDesc());
            //判断是否含有下属机构，含有则为true，没有则为false
            int nodeNum = queryNodeCountByDeptId(dept.getDepId());
            Boolean isParent = nodeNum > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code();
            demo.setIsParent(isParent);
            demotree.add(demo);
        }
        return demotree;
    }

    /**
     * 查询部门子节点的数量，用于确认是否有子部门
     *
     * @param deptId
     * @return
     * @throws Exception
     */
    public Integer queryNodeCountByDeptId(String deptId) throws Exception {
        return departmentMapper.selectCountByPDId(deptId);
    }

    /**
     * 查询部门详情
     *
     * @param deptId
     * @return
     * @throws Exception
     */
    public DepartmentVO findDeptById(String deptId) throws Exception {
        //获取部门信息
        DepartmentVO dept = StringUtils.isBlank(deptId) ? null : departmentMapper.selectByDeptId(deptId);
        return dept;
    }

    /**
     * 获取部门或机构的上级管理机构
     *
     * @param id
     * @return Organization
     * @throws Exception
     */
    public Organization getParentOrg(String id) throws Exception {
        Organization org = organizationMapper.selectOrgById(id);
        //如果为机构，则返回上级机构
        if (org.getOtype() == 0 && org.getParentOrgId() != null) {
            org = organizationMapper.selectOrgByOrgId(org.getParentOrgId());
            //如果为部门，且含有上级机构，返回上级机构
        } else if (org.getOtype() == 1 && org.getParentOrgId() != null) {
            org = organizationMapper.selectOrgByOrgId(org.getParentOrgId());
            //如果为部门，不含有上级机构，则循环查询上级，直到含有机构ID为止
        } else if (org.getOtype() == 1 && org.getParentOrgId() == null) {
            DepartmentVO departmentVO = departmentMapper.selectByDeptId(org.getOrgId());
            while (true) {
                if (departmentVO.getParentOrgId() != null) {
                    break;
                }
                departmentVO = departmentMapper.selectByDeptId(departmentVO.getParentDepId());
            }
            org = organizationMapper.selectOrgByOrgId(departmentVO.getParentOrgId());
        }
        return org;
    }

    /**
     * 新增部门
     *
     * @param dept
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> addDept(Department dept, Employee employee) throws Exception {
        if (StringUtils.isNotEmpty(dept.getParentDepId())) {
            Department param = departmentMapper.selectByDeptId(dept.getParentDepId());
            if (param != null)
                dept.setParentOrgId(param.getParentOrgId());
            else {
                dept.setParentOrgId(dept.getParentDepId());
                dept.setParentDepId(null);
            }
        }
        Map<String, Object> map = new HashMap<>();
        String creatorId = employee.getEmployeeId();
        //生成UUID
        dept.setDepId(UniqueUtil.uuid());
        dept.setCreatorId(creatorId);
        dept.setState(0);
        //对参数进行校验
        map = isBlank(dept);
        if ((Boolean) map.get("state") == false) return map;
        //生成添加时间   DateUtil.getTimeString()
        Date date = new Date();
        dept.setCreateTime(date);
        dept.setModifyTime(date);
        dept.setModifierId(creatorId);
        int num = departmentMapper.insertSelective(dept);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.ADD_OK : BackMessage.ADD_FAIL);
        return map;
    }

    /**
     * 删除部门,软删除，设置state=1
     *
     * @param deptId
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> delDept(String deptId) throws Exception {


        Map<String, Object> map = new HashMap<>();
        //判断deptId是否为空或是否含有下级部门，防止误删
        if (StringUtils.isBlank(deptId) || departmentMapper.selectCountByPDId(deptId) > 0) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", BackMessage.EMPTY_PARAMETER);
            return map;
        }
        Employee e = new Employee();
        e.setDepId(deptId);
        List<Employee> eList = employeeService.selectListEmploye(e);
        if (eList != null && eList.size() > 0) {
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "请解除人员信息关联后在来删除!");
            return map;
        }

        List<Roles> rolesList = rolesService.listRolesByIdOrg(deptId);
        if(rolesList != null && rolesList.size() > 0){
            map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            map.put("msg", "部门下有角色，请先删除角色!");
            return map;
        }
        int delNum = StringUtils.isBlank(deptId) ? -1 : departmentMapper.deleteByDeptId(deptId);
        map.put("state", delNum > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", delNum > 0 ? BackMessage.DEL_OK : BackMessage.DEL_FAIL);
        return map;
    }

    /**
     * 修改部门
     *
     * @param dept
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> updateDept(Department dept, Employee employee) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //设置修改者信息
        String modifyId = employee.getEmployeeId();
        dept.setModifierId(modifyId);
        //设置修改时间
        dept.setModifyTime(new Date());
        //对参数进行校验
        map = isBlank(dept);
        if ((Boolean) map.get("state") == false) return map;
        int num = departmentMapper.updateByPrimaryKeySelective(dept);
        map.put("state", num > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code());
        map.put("msg", num > 0 ? BackMessage.MODIFY_OK : BackMessage.MODIFY_FAIL);
        return map;
    }

    /**
     * 获取部门层级，使用枚举
     *
     * @param orgLevel
     * @return
     */
    public Enum[] getDeptLevel(String orgLevel) {
        if (!StringUtils.isBlank(orgLevel)) {
            if (OrganizationLevel.ORG_LEVEL_BRANCH.getCode().equals(orgLevel)) {
                //分公司的部门类别
                return DepartLevelCom.values();
            }
            //气矿的部门类别，待确认
            if (OrganizationLevel.ORG_LEVEL_GAS_FIELD.getCode().equals(orgLevel)) {
                return null;
            }
            if (OrganizationLevel.ORG_LEVEL_WORK_SPACE.getCode().equals(orgLevel)) {
                //作业区的部门类别
                return DepartLevelArea.values();
            }
        }
        return DepartLevel.values();
    }

    /**
     * ajax判断新部门名称是否重名
     *
     * @param department
     * @return
     * @throws Exception
     */
    public boolean checkDeptName(Department department) throws Exception {
        List<DepartmentVO> list = null;
        //判断上级部门ID是否为空
        if (!StringUtils.isBlank(department.getParentDepId())) {
            list = departmentMapper.selectByPDidAndName(department);
        }
        //判断上级机构ID是否为空
        if (!StringUtils.isBlank(department.getParentOrgId())) {
            list = departmentMapper.selectByPOidAndName(department);
        }
        //如果新部门名称的部门已经存在，则返回false
        if (list != null && list.size() > 0) return RespCodeEnum.RESP_CODE_ENUM_false.code();
        return RespCodeEnum.RESP_CODE_ENUM_true.code();
    }

    /**
     * 获取部门员工列表
     *
     * @param deptId
     * @return
     */
    public List<EmployeeSimpleVO> getEmpByDeptId(String deptId) {
        return departmentMapper.selectEmpByDeptId(deptId);
    }

    /**
     * @param orgId 组织机构Id
     */
    @Override
    public List<Ztree> getDeptZtreeByOrgId(String orgId) throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        List<Department> list = departmentMapper.selectDeptByOrgId(orgId);
        for (Department department : list) {
            Ztree ztree = new Ztree();
            ztree.setId(department.getDepId());
            ztree.setName(department.getDepName());
            if (department.getParentDepId() != null) {
                ztree.setpId(department.getParentDepId());
            } else {
                ztree.setpId(department.getParentOrgId());
            }
            ztree.setIconSkin(TreeIconSkin.ICON_DEPT.getDesc());
            ztree.setIsParent(true);
            ztreeList.add(ztree);
        }
        return ztreeList;
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量添加
     * @Date 2017/2/8 17:17
     */

    @Override
    public int insertList(List<Department> list) {
        return departmentMapper.insertList(list);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量修改
     * @Date 2017/2/8 17:17
     */
    @Override
    public int updateList(List<Department> list) {
        return departmentMapper.updateList(list);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量逻辑删除
     * @Date 2017/2/8 17:18
     */
    @Override
    public int deleteList(List<Department> list) {
        return departmentMapper.deleteList(list);
    }

    /**
     * 根据条件查询组织部门信息
     *
     * @param orgId
     * @param keyword
     * @return List<Ztree>
     * @Author 卢曼成
     */
    @Override
    public List<Ztree> queryDeptZtree(String orgId, String pOrgId, String keyword, String orgLevelId) {
        List<Ztree> ztList = new ArrayList<Ztree>();
        DepartmentVO dv = new DepartmentVO();
        Organization org = new Organization();
        org.setOrgLevelId(orgLevelId);
        if (StringUtils.isNotEmpty(keyword)) {
            dv.setKeyword(keyword);
            dv.setParentOrgId(pOrgId);
            List<DepartmentVO> depItemList = departmentMapper.selectByOrgItem(dv);
            List<Department> depList = departmentMapper.selectByPOIds(dv);
            if (depList != null && depList.size() > 0) {
                List<String> list = new ArrayList<String>();
                for (Department d : depList) {
                    list.add(d.getParentOrgId());
                }
                org.setList(list);
                org.setOrgId(pOrgId);
                org.setMaxLevelId("x");
                List<Organization> orgList = organizationMapper.queryOrgIdByList(org);
                DepartmentUtil.depAndOrgToTreeTrue(orgList, depList, ztList);
            } else {
                return ztList;
            }
        } else if (StringUtils.isNotEmpty(orgId)) {
            List<Organization> itemList = organizationMapper.selectByOrgItem(org);
            dv.setParentOrgId(orgId);
            List<DepartmentVO> depItemList = departmentMapper.selectByOrgItem(dv);
            List<Department> depList = departmentMapper.selectDeptByOrgId(orgId);
            org.setId(orgId);
            List<Organization> orgList = organizationMapper.selectOrgList(org);
            DepartmentUtil.depAndOrgToTree(orgList, itemList, depList, depItemList, pOrgId, ztList);
        } else {
            List<Organization> itemList = organizationMapper.selectByOrgItem(org);
            dv.setParentOrgId(pOrgId);
            List<DepartmentVO> depItemList = departmentMapper.selectByOrgItem(dv);
            List<Department> depList = departmentMapper.selectDeptByOrgId(pOrgId);
            org.setParentOrgId(pOrgId);
            List<Organization> orgList = organizationMapper.selectOrgLists(org);
            DepartmentUtil.depAndOrgToTree(orgList, itemList, depList, depItemList, pOrgId, ztList);
        }
        return ztList;
    }

    /**
     * 根据组织ID查询该组织下部门数量
     *
     * @param orgId
     * @return
     */
    @Override
    public int selectCountByPOId(String orgId) {
        return departmentMapper.selectCountByPOId(orgId);
    }

    /**
     * @Author 卢曼成
     * @Description 去重查询上级ID
     * @Date 2017/2/8 17:18
     */
    @Override
    public List<String> selectByListId(List<Department> list) {
        return departmentMapper.selectByListId(list);
    }


    /**
     * 部门对象参数校验方法
     *
     * @param department
     * @return
     */
    private Map<String, Object> isBlank(Department department) {
        Map<String, Object> map = new HashMap<>();
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
        //校验部门名称是否为空
        if (StringUtils.isBlank(department.getDepName())) {
            map.put("msg", "部门名称不能为空！");
            return map;
        }
        //校验部门名称长度
        if (department.getDepName().length() > 255) {
            map.put("msg", "部门名称长度不能超过255个字符！");
            return map;
        }
        //校验部门ID是否为空，主要用于新增和修改
        if (StringUtils.isBlank(department.getDepId())) {
            map.put("msg", "部门ID不能为空！");
            return map;
        }
        //校验部门ID长度，防止手动输入
        if (department.getDepId().length() > 32) {
            map.put("msg", "部门ID长度不能超过32个字符！");
            return map;
        }
        map.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
        return map;
    }

    /**
     * @param employee
     * @return 根据当前登录人查询到当前登录人的部门信息 和 组织机构信息
     */
    @Override
    public List<Ztree> initMyDeptmentAndChildDept(Employee employee) {
        logger.info("initMyDeptmentAndChildDept-->employee--->" + employee.getOrgId());
        List<Ztree> resInitDeptList = new ArrayList<>();
        // 当前登录人
        if (StringUtils.isNotEmpty(employee.getDepId()) && StringUtils.isNotEmpty(employee.getOrgId())) {
            /**
             * 1:获取当前部门 ， 当前部门的组织机构 ， 然后查询当前部门的下级部门是否存在
             */
            // 根据当前人员的组织机构查询到当前部门的同级部门 和 当前部门所属组织机构下的所有部门和组织机构
            Organization organization = jsmOrganizationService.selectOrgByOrgId(employee.getOrgId());
            if (organization != null && StringUtils.isNotEmpty(organization.getOrgLevelId())) {
                List<Organization> offsetOrgList = new ArrayList<>();
                offsetOrgList.add(organization);
                try {
                    resInitDeptList.addAll(jsmOrganizationService.setZtree(offsetOrgList));
                    List<Department> deptList = departmentMapper.selectDeptByOrgId(organization.getOrgId());
                    if (deptList != null && deptList.size() > 0) {
                        for (Department dept : deptList) {
                            Ztree ztree = new Ztree();
                            ztree.setId(dept.getDepId());
                            ztree.setName(dept.getDepName());
                            ztree.setpId(dept.getParentOrgId());
                            ztree.setIconSkin(TreeIconSkin.ICON_DEPT.getDesc());
                            ztree.setIsParent(false);
                            ztree.setOpen(true);
                            resInitDeptList.add(ztree);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // 查询当前组织机构下的组织机构
                try {
                    List<Organization> childRenOrglist = jsmOrganizationService.queryNodeByOrgId(employee.getOrgId());
                    //
                    if (childRenOrglist != null && childRenOrglist.size() > 0) {
                        for (Organization ot : childRenOrglist) {
                            List<Department> otChildDeptList = departmentMapper.selectDeptByOrgId(ot.getOrgId());
                            if (otChildDeptList != null && otChildDeptList.size() > 0) {
                                for (Department dt : otChildDeptList) {
                                    Ztree zt = new Ztree();
                                    zt.setId(dt.getDepId());
                                    zt.setName(dt.getDepName());
                                    zt.setpId(dt.getParentOrgId());
                                    zt.setIconSkin(TreeIconSkin.ICON_DEPT.getDesc());
                                    zt.setIsParent(false);
                                    zt.setOpen(true);
                                    resInitDeptList.add(zt);
                                }
                            }
                        }
                        resInitDeptList.addAll(jsmOrganizationService.setZtree(childRenOrglist));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

/*            if(StringUtils.isNotEmpty(employee.getOrgId())){
                Map btMap = new HashMap<>();
                btMap.put("bottomLevel","3");
                btMap.put("lessLevel","5");
                btMap.put("orgId",organization.getOrgId());
                List<Organization> bttOrgList = organizationMapper.selectBottomToTopOrgList(btMap);
                if(bttOrgList != null && bttOrgList.size() > 0){
                    try {
                        List<Ztree>  orgList = jsmOrganizationService.setZtree(bttOrgList);
                        resInitDeptList.addAll(orgList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }*/
        } else {
            // 则是组织机构下的人，组织机构下挂载人，只能是场站和井站
            /***
             * 1:查看当前组织机构是否是作业区 ， 如果是作业区以上的组织机构，这查询查询作业区以上机构 ， 然后向下组织机构遍历{遍历为部门和组织机构}
             */
            Map btMap = new HashMap<>();
            btMap.put("bottomLevel", "3");
            btMap.put("lessLevel", "5");
            btMap.put("orgId", employee.getOrgId());
            // 向上查询， 包含了本组织机构
           /* List<Organization> bttOrgList = organizationMapper.selectBottomToTopOrgList(btMap);
            if(bttOrgList != null && bttOrgList.size() > 0){
                try {
                    resInitDeptList.addAll(jsmOrganizationService.setZtree(bttOrgList));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }*/
            // 查询向下 查询下级组织机构
            List<Organization> childOrgList = jsmOrganizationService.selectOrgListByEmployee(employee.getOrgId(), "5", "1");
            if (childOrgList != null && childOrgList.size() > 0) {
                // 项目组织机构
                for (Organization org : childOrgList) {
                    // 查询组织机构下的部门并加载
                    try {
                        List<Ztree> ztrees = getDeptZtreeByOrgId(org.getOrgId());
                        if (ztrees != null && ztrees.size() > 0) {
                            resInitDeptList.addAll(ztrees);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    resInitDeptList.addAll(jsmOrganizationService.setZtree(childOrgList));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }

        List<Ztree> deptList = new ArrayList<>();
        Map<String, Ztree> isEditMap = new HashMap<>();
        if (resInitDeptList != null && resInitDeptList.size() > 0) {
            for (Ztree ztree : resInitDeptList) {
                isEditMap.put(ztree.getId(), ztree);
            }
        }
        List<Ztree> orgZtreeList = new ArrayList<>();
        // 去掉重复
        if (isEditMap != null && isEditMap.size() > 0) {
            for (Map.Entry<String, Ztree> entry : isEditMap.entrySet()) {
                Ztree ztree = entry.getValue();
                ztree.setIsParent(false);
                logger.info("employee--->" + employee.getOrgId() + "---<--->" + ztree.getpId() + "---->" + employee.getOrgId().equals(ztree.getpId()));
                if (employee.getOrgId().equals(ztree.getId())) {
                    ztree.setOpen(true);
                } else {
                    ztree.setOpen(false);
                }
                if (ztree.getIconSkin().equals(TreeIconSkin.ICON_DEPT.getDesc())) {
                    deptList.add(ztree);
                } else {
                    orgZtreeList.add(ztree);
                }

            }
        }
        if (orgZtreeList != null && orgZtreeList.size() > 0) {
            deptList.addAll(orgZtreeList);
        }
        return deptList;
    }

    /**
     * 根据组织ID查询部门集合
     *
     * @param orgId
     * @return
     */
    @Override
    public List<Department> selectDeptByOrgId(String orgId) {
        return departmentMapper.selectDeptByOrgId(orgId);
    }

    /**
     * 根据组织ID查询部门集合
     *
     * @param orgId
     * @return
     */
    @Override
    public List<DepartmentVO> selectByPOId(String orgId) {
        return departmentMapper.selectByPOId(orgId);
    }
}
